package com.sky.service.admin.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.dto.OrdersCancelDTO;
import com.sky.dto.OrdersDTO;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersRejectionDTO;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.mapper.User.OrderDetailMapper;
import com.sky.mapper.admin.OrdersMapper;
import com.sky.result.PageResult;
import com.sky.service.admin.OrderService;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;

    /**
     * 分页查询
     *
     * @param ordersPageQueryDTO
     * @return
     */
    public PageResult page(OrdersPageQueryDTO ordersPageQueryDTO) {

        //分页查询
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> page = ordersMapper.pageQuery(ordersPageQueryDTO);

        //订单菜品信息查询
        List<OrderVO> orderVOList = getOrderVOList(page);

        return new PageResult(page.getTotal(), orderVOList);
    }

    private List<OrderVO> getOrderVOList(Page<Orders> page) {
        // 需要返回订单菜品信息，自定义OrderVO响应结果
        List<OrderVO> orderVOList = new ArrayList<>();

        List<Orders> ordersList = page.getResult();

        if (ordersList != null && ordersList.size() > 0) {
            for (Orders orders : ordersList) {

                //获取到具体地址
                AddressBook ressBook = ordersMapper.getRessBook(orders.getAddressBookId());
                String address = ressBook.getProvinceName() + ressBook.getCityName() + ressBook.getDistrictName() + ressBook.getDetail();
                orders.setAddress(address);

                // 将共同字段复制到OrderVO
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);

                //获取到菜品名和数量
                String orderDishes = getOrderDishesStr(orders);

                // 将订单菜品信息封装到orderVO中，并添加到orderVOList
                orderVO.setOrderDishes(orderDishes);
                orderVOList.add(orderVO);
            }
        }

        return orderVOList;
    }

    /**
     * 根据订单id获取菜品信息字符串
     *
     * @param orders
     * @return
     */
    private String getOrderDishesStr(Orders orders) {
        // 查询订单菜品详情信息（订单中的菜品和数量）
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());

        // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）
        List<String> orderDishList = new ArrayList<>();
        for (OrderDetail orderDetail : orderDetailList) {
            String orderDish = orderDetail.getName() + "*" + orderDetail.getNumber() + ";";
            orderDishList.add(orderDish);
        }

       /* List<String> orderDishList = orderDetailList.stream().map(x -> {
            String orderDish = x.getName() + "*" + x.getNumber() + ";";
            return orderDish;
        }).collect(Collectors.toList());*/

        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", orderDishList);
    }


    /**
     * 各个状态的订单数量统计
     *
     * @return
     */
    public OrderStatisticsVO getOrderStatistics() {
        //待接单数量
        Orders orders = new Orders();
        orders.setStatus(Orders.REFUND);
        Integer toBeConfirmed = ordersMapper.getCount(orders);
        //待派送数量
        orders.setStatus(Orders.CONFIRMED);
        Integer confirmed = ordersMapper.getCount(orders);

        //派送中数量
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        Integer deliveryInProgress = ordersMapper.getCount(orders);

        OrderStatisticsVO order = OrderStatisticsVO.builder()
                .toBeConfirmed(toBeConfirmed)
                .confirmed(confirmed)
                .deliveryInProgress(deliveryInProgress)
                .build();

        return order;
    }

    /**
     * 查询订单信息
     *
     * @return
     */
    public OrderVO saveDetails(Long id) {
        Orders orders = ordersMapper.getAll(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);

        List<OrderDetail> detail = ordersMapper.getDetail(orderVO.getId());
        orderVO.setOrderDetailList(detail);

        log.info("订单数据：{}", orderVO);
        return orderVO;
    }

    /**
     * 接单
     *
     * @param id
     */
    public void updateConfirm(Long id) {
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(Orders.CONFIRMED);

        ordersMapper.updateConfirm(orders);
    }

    /**
     * 拒单
     *
     * @param ordersRejectionDTO
     */
    @Transactional
    public void RejectionOrder(OrdersRejectionDTO ordersRejectionDTO) {
        Orders orders = Orders.builder()
                .id(ordersRejectionDTO.getId())
                .rejectionReason(ordersRejectionDTO.getRejectionReason())
                .status(Orders.CANCELLED)
                .build();
        ordersMapper.updateConfirm(orders);
    }

    /**
     * 取消订单
     *
     * @param ordersCancelDTO
     */
    public void cancelOrder(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = Orders.builder()
                .id(ordersCancelDTO.getId())
                .cancelReason(ordersCancelDTO.getCancelReason())
                .status(Orders.CANCELLED)
                .cancelTime(LocalDateTime.now())
                .build();
        ordersMapper.updateConfirm(orders);
    }

    /**
     * 派送订单
     *
     * @param id
     */
    public void orderDelivery(Long id) {
        Orders orders = Orders.builder().id(id).status(Orders.DELIVERY_IN_PROGRESS).build();
        ordersMapper.updateConfirm(orders);
    }

    /**
     * 送达
     *
     * @param id
     */
    public void orderComplete(Long id) {
        Orders orders = Orders.builder().id(id).status(Orders.COMPLETED).deliveryTime(LocalDateTime.now()).build();
        ordersMapper.updateConfirm(orders);
    }
}
